package consul

import (
	"fmt"
	"github.com/google/wire"
	consulApi "github.com/hashicorp/consul/api"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
)

// consul 服务发现中心
type Options struct {
	Addr string
}

func NewOptions(v *viper.Viper) (*Options, error) {
	var (
		err error
		o   = new(Options)
	)
	if err = v.UnmarshalKey("consul", o); err != nil {
		return nil, errors.Wrap(err, "viper 解析配置文件 consul 失败")
	}
	return o, nil
}

// 实例化consul 客户端
func New(o *Options) (*consulApi.Client, error) {
	config := consulApi.DefaultConfig()
	config.Address = o.Addr
	consulApi, err := consulApi.NewClient(config)
	if err != nil {
		return nil, errors.Wrap(err, "创建consul 客户端失败")
	}
	fmt.Println("实例化成功", consulApi)
	return consulApi, nil
}

var ProviderSet = wire.NewSet(New, NewOptions)
